﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace AutoPartsSearch.Web.Infrastructure.Cache
{
    public static class CacheHelper
    {
        public static void AddToCache(object value, string key, int timeInMinutes)
        {
            if (value != null)
            {
                System.Web.HttpContext.Current.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(timeInMinutes),
                                                            System.Web.Caching.Cache.NoSlidingExpiration);
            }
        }

        public static object GetFromCache(string key)
        {
            return HttpContext.Current.Cache.Get(key);
        }

        public static void ResetCache()
        {
            // retrieve application Cache enumerator
            IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();
            // copy all keys that currently exist in Cache
            while (enumerator.MoveNext())
            {
                HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
            }
        }

        public static string CreateKey(params object[] parameters)
        {
            var sb = new StringBuilder();
            foreach (var parameter in parameters)
            {
                var value = parameter == null ? "null" : parameter.ToString();
                sb.Append("$" + value);
            }
            return sb.ToString();
        }
    }
}